package com.lxz.nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class TimeServer {
	public static void main(String[] args){
		int port = 1234;
		if(args != null && args.length > 0){
			try{
				port = Integer.valueOf(args[0]);
			}catch(NumberFormatException e){
				//采用默认值
			}
		}
		MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
		new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();
	}
	
}

class MultiplexerTimeServer implements Runnable{
	private Selector selector;
	private ServerSocketChannel servChannel;
	private volatile boolean stop;
	
	/**
	 * 初始化多路复用器、绑定监听端口
	 * @param port
	 */
	public MultiplexerTimeServer(int port){
		try{
			selector = Selector.open();//创建Reactor线程
			servChannel = ServerSocketChannel.open();//用于监听客户端的连接，它是所有客户端连接的父管道
			servChannel.configureBlocking(false);//设置为非阻塞模式
			servChannel.socket().bind(new InetSocketAddress(port), 1024);//绑定监听端口，并将backlog设置为1024
			servChannel.register(selector, SelectionKey.OP_ACCEPT);//将ServerSocketChannel注册到Reactor线程的多路复用器Selector上，监听ACCEPT事件
			System.out.println("The time server is start in port : " + port);
		}catch(IOException e){
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public void stop(){
		this.stop = true;
	}
	
	public void run() {
		while(!stop){
			try{
				selector.select(1000);
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> it = selectionKeys.iterator();
				SelectionKey key = null;
				while(it.hasNext()){//多路复用器在线程run方法的无线循环体内轮询准备就绪的Key
					key = it.next();
					it.remove();
					try{
						handleInput(key);
					}catch(Exception e){
						if(key != null){
							key.cancel();
							if(key.channel() != null){
								key.channel().close();
							}
						}
					}
				}
			}catch(Throwable t){
				t.printStackTrace();
			}
		}
		
		//多路复用器关闭后，所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭，所以不需要重复释放资源
		if(selector != null){
			try{
				selector.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	private void handleInput(SelectionKey key) throws IOException{
		if(key.isValid()){
			//处理新接入的请求消息
			if(key.isAcceptable()){
				//Accept the new connection
				ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
				SocketChannel sc = ssc.accept();//多路复用器监听到有新的客户端接入，处理新的接入请求，完成TCP三次握手，建立物理链路
				sc.configureBlocking(false);//为客户端链路设置为非阻塞模式
				//Add the new connection to the selector
				sc.register(selector, SelectionKey.OP_READ);//将新接入的客户端连接注册到Reactor线程的多路复用器上，监听读操作，用来读取客户端发送的网络消息
			}
			if(key.isReadable()){
				//Read the data
				SocketChannel sc = (SocketChannel)key.channel();
				ByteBuffer readBuffer = ByteBuffer.allocate(1024);
				int readBytes = sc.read(readBuffer);//异步读取客户端请求消息到缓冲区
				if(readBytes > 0){
					readBuffer.flip();//将缓冲区当前的limit设置为position，position设置为0，用于后续对缓冲区的操作
					byte[] bytes = new byte[readBuffer.remaining()];
					readBuffer.get(bytes);
					String body = new String(bytes, "UTF-8");
					System.out.println("The time server receive order : " + body);
					String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? 
							new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
					doWrite(sc, currentTime);
				} else if(readBytes < 0){
					//对端链路关闭
					key.cancel();
					sc.close();
				}else{
					;//读到0字节，忽略
				}
			}
		}
	}
	
	private void doWrite(SocketChannel channel, String response) throws IOException{
		if(response != null && response.trim().length() > 0){
			byte[] bytes = response.getBytes();
			ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
			writeBuffer.put(bytes);
			writeBuffer.flip();
			channel.write(writeBuffer);
		}
	}
}